/**
 * 
 */
package com.huniu.analysis.hive;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.huniu.analysis.colony.ILeaderBeeAnalyse;
import com.huniu.analysis.colony.LeaderBeeAnalyseImpl;
import com.huniu.analysis.model.QualityXMLProperty;
import com.huniu.links.model.ModelXMLProperty;

/**
 * @author zandy (chenheng)
 * 
 */
public class LeaderBeeAnalysePoolImpl implements ILeaderBeeAnalysePool {
	private static final Logger logger = Logger.getLogger(LeaderBeeAnalysePoolImpl.class); 
	private List<File> qualityFiles;

	public void setQualityFiles(List<File> qualityFiles) {
		this.qualityFiles = qualityFiles;
	}

	@SuppressWarnings("unchecked")
	public void analyse() {
		ExecutorService executor = Executors.newCachedThreadPool();
		SAXReader reader = new SAXReader();
		logger.info("Load Quality Files : " + qualityFiles.size());
		for (File file : qualityFiles) {
			try {
				Document document = reader.read(file);
				Element root = document.getRootElement();
				Iterator<Element> iterator = root
						.elementIterator(QualityXMLProperty.ELEMENT);
				while (iterator.hasNext()) {
					logger.info("Start a leader bee to analyse html quality ");
					ILeaderBeeAnalyse leaderAnalyse = new LeaderBeeAnalyseImpl();
					leaderAnalyse.setHtmlQuality(iterator.next());
					executor.execute(leaderAnalyse);
				}
			} catch (DocumentException e) {
				
			}
			generateAnalysedFile(file);
		}
		executor.shutdown();
	}
	
	private void generateAnalysedFile(File file) {
		String processedFileName = file.getAbsolutePath()
				+ ModelXMLProperty.ANALYSED_EXTENSION;
		File processedFile = new File(processedFileName);
		file.renameTo(processedFile);
	}
}
